package com.tihi.util;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.os.Handler;
import android.os.Looper;

/**
 * 异步
 * @author duantihi
 *
 * @date 2016-1-31 下午5:12:29
 */
public class TihiAsyncTask<T> {
	
	private ExecutorService service;
	private Handler handler;
	
	public interface IAsyncTaskListener<T> {
		T onTask();
		void onResult(T t);
	}
	
	private IAsyncTaskListener<T> listener;
	
	public TihiAsyncTask(IAsyncTaskListener<T> listener) {
		service = Executors.newFixedThreadPool(1);
		handler = new Handler(Looper.getMainLooper());
		this.listener = listener;
	}
	
	public void submit() {
		service.submit(new Runnable() {
			
			@Override
			public void run() {
				if(listener != null) {
					final T t = listener.onTask();
					handler.post(new Runnable() {
						
						@Override
						public void run() {
							listener.onResult(t);
						}
					});
				}
			}
		});
	}
	
}
